﻿using System;
using System.Web;
using System.Configuration;
using System.Web.UI;
using Crosland.Automotriz.Seguridad.Entity;
using Crosland.Automotriz.Seguridad.Business;
using System.Collections.Generic;
using System.Net.Mail;
using Crosland.Automotriz.Seguridad.ControlExeption;
using Crosland.Automotriz.Logic;


namespace Crosland.Automotriz.Web.Extranet
{
    public partial class wFrmLoginExtranet : System.Web.UI.Page
    {
        LecturaTicketSAP BL_SAP = new LecturaTicketSAP();
        clsUsuarioLogic BL_login = new clsUsuarioLogic();
        MailMessage mail = new MailMessage();
        string des_email = "";
        string clave = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["MYSAPSSO2"] != null)
            {
                Logear2();
                return;
            }

            if (!IsPostBack)
            {
               this.VerificarEstadoSesion();
            }
        }

        protected void btnIngresar_Click(object sender, EventArgs e)
        {
            this.Logear();
        }

        protected void Logear()
        {
           
        }

        protected void VerificarEstadoSesion()
        {
            //Session["User"] = "20107113127";

            if (Session[DatosSesion.User] != null)
            {
                Response.Redirect(Constantes.PaginaLogin);
            }
        }

        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            this.RecuperarPassword();
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            this.pnlLogin.Visible = true;
            this.pnlRecuperar.Visible = false;
        }
  
        protected void lblRecuperarClave_Click(object sender, EventArgs e)
        {
            this.pnlRecuperar.Visible = true;
            this.pnlLogin.Visible = false;
            this.pnlAcceso.Visible = false;
        }

        protected void RecuperarPassword()
        {
            if (txtEmail.Text.Trim() == string.Empty)
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "Ingrese su Email por favor ";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
            else
            {

                this.RecuperaEmail();
                if (des_email == string.Empty)
                {
                    lblMsj.Text = string.Empty;
                    lblMsj.Text = "El email ingresado no está registrado";
                    string scriptExeption = "ShowPopupLogin();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);

                }
                else
                {
                    this.ActualizaClave();
                    this.EnviarPasswordNuevo();
                    txtEmail.Text = string.Empty;

                }
            }
        }

        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            this.SolicitarAcceso();
        }

        protected void SolicitarAcceso()
        {          
         
        }

        protected void lblAcceso_Click(object sender, EventArgs e)
        {
         
        }

        protected void btnCancelarAcceso_Click(object sender, EventArgs e)
        {
        
            this.pnlAcceso.Visible = false;
            this.pnlLogin.Visible = true;
            this.pnlRecuperar.Visible = false;
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUsuario.Text == string.Empty)
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "Debe ingresar su usuario.";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
            else if (txtPassword.Text == string.Empty)
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "Debe ingresar su contraseña.";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
            else
            {
                this.Logear2();
            }
        }

        void Logear2()
        {
           

            if (Request.Cookies["MYSAPSSO2"] != null)
            {
                HttpCookie cookie = Request.Cookies["MYSAPSSO2"];

                string ticket = cookie.Value;
                string rutaSapSecu = Server.MapPath("~/DLL_SAP/sapsecu.dll");
                string rutaVerify = Server.MapPath("~/DLL_SAP/verify.pse");

                string usuario = BL_SAP.LeerCookiesSAP(ticket, rutaSapSecu, rutaVerify);

                List<T_SEG_USUARIO> listaUsuario = BL_login.listarUser(usuario);

                //string password = BL_login.DesEncriptarUser(listaUsuario[0].DES_PASSWORD);

                if (listaUsuario.Count > 0)
                {

                    Session[DatosSesion.User] = usuario;
                    Session["User"] = usuario;
                    Session["UserCliente"] = usuario;
                    Session["TipoUsuario"] = listaUsuario[0].ID_TIPO_USUARIO;
                    this.RegistrarHistoriallogTrue();
                    Response.Redirect(@"~\Seguridad\wFrmDefault.aspx?id=3");
                    

                }
                else
                {
                    this.RegistrarHistorialLogError();
                    lblMsj.Text = string.Empty;
                    lblMsj.Text = "El nombre de usuario o la contraseña que ingresaste es incorrecto.";
                    string scriptExeption = "ShowPopupLogin();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
                
                }


            }
            else
            {

                try
                {
                    string username = this.txtUsuario.Text;
                    string password = this.txtPassword.Text;

                    string resultado = BL_login.ValidarUsuarioExterno(username, password);
                    List<T_SEG_USUARIO> listaUsuario = BL_login.listarUser(username);
                    if (resultado == ResultadoLogin.LoginOk)
                    {
                        Session[DatosSesion.User] = username;
                        Session["User"] =txtUsuario.Text;
                        Session["UserCliente"] = txtUsuario.Text;
                        Session["TipoUsuario"] = listaUsuario[0].ID_TIPO_USUARIO;
                        this.RegistrarHistoriallogTrue();
                        Response.Redirect("~/Seguridad/wFrmDefault.aspx",false);
                    }
                    else
                    {
                        this.RegistrarHistorialLogError();
                        lblMsj.Text = string.Empty;
                        lblMsj.Text = "El nombre de usuario o la contraseña que ingresaste es incorrecto.";
                        string scriptExeption = "ShowPopupLogin();";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
                    }
                }              
                catch (Exception ex)
                {
                    lblMsj.Text = string.Empty;
                    lblMsj.Text = "El nombre de usuario o la contraseña que ingresaste es incorrecto.";
                    string scriptExeption = "ShowPopupLogin();";
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
                }
            

            }

           

           
        }

        public struct ResultadoLogin
        {
            /// <summary>
            /// El login es correcto
            /// </summary>
            public const string LoginOk = "OK";

            /// <summary>
            /// El usuario no existe
            /// </summary>
            public const string LoginUserNoxiste = "seg_user_noexiste";

            /// <summary>
            /// El usuario esta inactivo
            /// </summary>
            public const string LoginUserInactivo = "seg_user_noactivo";

            /// <summary>
            /// El password ingresado no es correcto
            /// </summary>
            public const string LoginPwdIncorrecto = "seg_pws_incorrecto";
        }

        void RegistrarHistorialLogError()
        {
            clsT_Seg_Historial_LogLogic clst_seg_historial_log = new clsT_Seg_Historial_LogLogic();
            T_SEG_HISTORIAL_LOG t_seg_historial_log = new T_SEG_HISTORIAL_LOG();
            t_seg_historial_log.ID_SEG_HISTORIAL_LOG = clst_seg_historial_log.UltimoNumeroLog_historial() + 1;
            t_seg_historial_log.ID_USUARIO = txtUsuario.Text;
            t_seg_historial_log.FECHA = DateTime.Now;
            t_seg_historial_log.RESULTADO = false;
            clst_seg_historial_log.Insertar(t_seg_historial_log);
        }

        void RegistrarHistoriallogTrue()
        {
            clsT_Seg_Historial_LogLogic clst_seg_historial_log = new clsT_Seg_Historial_LogLogic();
            T_SEG_HISTORIAL_LOG t_seg_historial_log = new T_SEG_HISTORIAL_LOG();
            t_seg_historial_log.ID_SEG_HISTORIAL_LOG = clst_seg_historial_log.UltimoNumeroLog_historial() + 1;
            t_seg_historial_log.ID_USUARIO = txtUsuario.Text;
            t_seg_historial_log.FECHA = DateTime.Now;
            t_seg_historial_log.RESULTADO = true;
            clst_seg_historial_log.Insertar(t_seg_historial_log);
            Global.id_seg_historial = t_seg_historial_log.ID_SEG_HISTORIAL_LOG;
        }

        void EnviarPasswordNuevo()
        {
            try
            {
                mail.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["UserNameSMTP"]);
                mail.To.Add(txtEmail.Text);
                mail.Subject = ("Password Nuevo ");
                mail.Body = ("Su nuevo password es : " + clave);
                SmtpClient s = new SmtpClient();
                s.Host = ConfigurationManager.AppSettings["EmailServer"];
                s.Port = 25;
                s.EnableSsl = false;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["PasswordSMTP"]);
                s.Send(mail);

                lblMsj.Text = string.Empty;
                lblMsj.Text = "Su password ha sido enviado a su email";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
            catch
            {
                lblMsj.Text = string.Empty;
                lblMsj.Text = "No se pudo enviar al email por problemas de conexion";
                string scriptExeption = "ShowPopupLogin();";
                ScriptManager.RegisterStartupScript(this, typeof(Page), "carga", scriptExeption, true);
            }
        }

        void RecuperaEmail()
        {

            try
            {
                List<T_SEG_USUARIO> list = BL_login.listaEmail(txtEmail.Text);
                if (list[0].DES_EMAIL == string.Empty)
                {

                }
                else
                {
                    des_email = list[0].DES_EMAIL;
                }
            }
            catch (Exception ex)
            {
               
            }      
        }

        void ActualizaClave()
        {
            clave = BL_login.GenerarPass(1, 8);
            BL_login.actualizarPassword(BL_login.EncriptarPasswordUser(clave), des_email);

        }

    }
}